﻿using FrmMain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.ComponentModel;
using System.Collections;

namespace FrmMain.Util
{
    public static class EnumExtension
    {
        /// <summary>
        /// 获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<ComDictionary> GetEnums<T>()
        {
            List<ComDictionary> list = new List<ComDictionary>();

            Type type = typeof(T);
            foreach (FieldInfo field in type.GetFields())
            {
                if (field.FieldType.IsEnum)
                {
                    ComDictionary model = new ComDictionary();
                    string key = string.Empty;
                    object[] attrs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (attrs.Count() > 0)
                    {
                        var attr = attrs[0] as DescriptionAttribute;
                        key = attr.Description;

                        model.Key = key;
                    }
                    else
                    {
                        model.Key = field.Name;
                    }
                    var value = GetEnumValue(type, field.Name);
                    model.Value = value.ToString();
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 根据枚举name获取对应值
        /// </summary>
        /// <param name="enumType">类型</param>
        /// <param name="enumName">枚举name</param>
        /// <returns></returns>
        public static int GetEnumValue(Type enumType, string enumName)
        {
            try
            {
                if (!enumType.IsEnum)
                    throw new ArgumentException("enumType必须是枚举类型");
                var values = Enum.GetValues(enumType);
                var ht = new Hashtable();
                foreach (var val in values)
                {
                    ht.Add(Enum.GetName(enumType, val), val);
                }
                return (int)ht[enumName];
            }
            catch (Exception e)
            {
                throw e;
            }
        }


    }
}
